package com.demo.employees.dao.impl;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.demo.employees.dao.EmployeeDAO;
import com.demo.employees.model.Employee;

/**
 * DAO的MyBatis实现类
 * @author: jie.deng
 * @time: 2017年4月15日 上午1:38:38
 */
//@Component
public class EmployeeDAOMyBatisImpl implements EmployeeDAO {
	
	@Autowired
	private SqlSessionFactory sqlSessionFactory;
//	private static final String MYBATIS_RESOURCE = "mybatis/mybatis-config.xml";
//
//	public EmployeeDAOMyBatisImpl() {
//		super();
//		try {
//			InputStream inputStream = Resources.getResourceAsStream(MYBATIS_RESOURCE);
//			sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//	}

	@Override
	public void saveEmployee(Employee employee) {
		SqlSession session = sqlSessionFactory.openSession();
		try {
			session.insert("com.demo.employees.dao.EmployeeDAO.saveEmployee", employee);
			session.commit();
		} finally {
			session.close();
		}	
	}

	@Override
	public void updateEmployee(Employee employee) {
		SqlSession session = sqlSessionFactory.openSession();
		try {
			session.update("com.demo.employees.dao.EmployeeDAO.updateEmployee", employee);
			session.commit();
		} finally {
			session.close();
		}	
	}

	@Override
	public Employee getById(Long id) {
		SqlSession session = sqlSessionFactory.openSession();
		Employee employee = null;
		try {
			employee = (Employee)session.selectOne("com.demo.employees.dao.EmployeeDAO.getById", id);
		} finally {
			session.close();
		}		
		return employee;
	}

	@Override
	public List<Employee> findAll() {
		SqlSession session = sqlSessionFactory.openSession();
		List<Employee> list = null;
		try {
			list = session.selectList("com.demo.employees.dao.EmployeeDAO.findAll");
		} finally {
			session.close();
		}
		return list;
	}

	@Override
	public void deleteById(Long id) {
		SqlSession session = sqlSessionFactory.openSession();
		try {
			session.delete("com.demo.employees.dao.EmployeeDAO.deleteById", id);
			session.commit();
		} finally {
			session.close();
		}
	}

	@Override
	public int getCount() {
		SqlSession session = sqlSessionFactory.openSession();
		int count = 0;
		try {
			count = session.selectOne("com.demo.employees.dao.EmployeeDAO.getCount");
		} finally {
			session.close();
		}		
		return count;
	}

}
